package com.ccp.dev.qbdms.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.ccp.dev.core.basic.annotion.Action;
import com.ccp.dev.core.basic.consts.UrlConstants;
import com.ccp.dev.core.basic.internationalization.SysBaseController;
import com.ccp.dev.core.basic.util.ContextUtil;
import com.ccp.dev.core.basic.web.query.QueryFilter;
import com.ccp.dev.core.util.BeanUtils;
import com.ccp.dev.core.util.RequestUtil;
import com.ccp.dev.core.util.StringUtil;
import com.ccp.dev.core.util.log.SysAuditThreadLocalHolder;
import com.ccp.dev.qbdms.consts.ZhiLiangConst;
import com.ccp.dev.qbdms.enums.FlowStatusEnum;
import com.ccp.dev.qbdms.expimp.util.AbstractExpUtil;
import com.ccp.dev.qbdms.expimp.util.AuxiliaryUtil;
import com.ccp.dev.qbdms.model.WQbdTrustPeople;
import com.ccp.dev.qbdms.service.WQbdTrustPeopleService;
import com.ccp.dev.qbdms.util.BaseUtil;
import com.ccp.dev.qbdms.util.ProjectUUIDUtils;
import com.ccp.dev.qbdms.util.StructureModifyUtil;
import com.ccp.dev.system.model.SysOrg;
import com.ccp.dev.system.model.SysRole;
import com.ccp.dev.system.model.SysUser;
import com.ccp.dev.system.service.SysOrgService;
import com.ccp.dev.workflow.model.ProcessRun;
import com.ccp.dev.workflow.model.TaskOpinion;
import com.ccp.dev.workflow.model.bpm.ProcessCmd;
import com.ccp.dev.workflow.service.ProcessRunService;
import com.ccp.dev.workflow.service.TaskOpinionService;
import com.google.common.collect.Maps;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * 质量信得过职工管理 信息操作处理控制器
 *
 * @author 王明亮
 * @date 2020-07-02 15:30:24
 */
@Controller
/**
 * 请将此名称添加到日志开关
 */
@Action(customModel = "质量信得过职工管理")
@RequestMapping("/qbdms/wQbdTrustPeople")
public class WQbdTrustPeopleController extends SysBaseController {
    @Resource
    private WQbdTrustPeopleService wQbdTrustPeopleService;
    @Resource
    private SysOrgService sysOrgService;
    @Resource
    private ProcessRunService processRunService;
    @Resource
    private TaskOpinionService taskOpinionService;

    /**
     * 功能描述: 跳转到首页
     *
     * @return: java.lang.String
     * @auther: 王明亮
     * @date: 2020-07-02 15:30:24
     */
    @RequestMapping(UrlConstants.VIEW_DISPATCH_PREFIX + UrlConstants.MODULE_FUNCTION_LIST)
    @Action(description = "跳转到质量信得过职工管理首页", exectype = "页面跳转日志")
    public String viewList(HttpServletRequest request, ModelMap modelMap) {
        // 当前系统等级
        BaseUtil.SystemLevel currentSystemLevel = BaseUtil.getCurrentSystemLevel();
        modelMap.put("currentSystemLevel", currentSystemLevel);

        List<SysOrg> listOrg = new ArrayList<SysOrg>();
        listOrg = sysOrgService.queryAll();
        modelMap.put("researchRoomList", JSON.toJSONString(listOrg));

        SysRole sysRole = (SysRole) request.getSession().getAttribute(SysRole.CURRENT_SYSROLE);
        modelMap.put("rolealis", sysRole.getAlias());
        // 当前登录用户id
        modelMap.put("currentUserId", ContextUtil.getCurrentUserId());
        return "wQbdTrustPeople/list";
    }

    /**
     * 功能描述: 附带检索条件的分页查询
     *
     * @param: [request] http请求
     * @return: java.lang.Object
     * @auther: 王明亮
     * @date: 2020-07-02 15:30:24
     */
    @RequestMapping(UrlConstants.MODULE_FUNCTION_LIST)
    @ResponseBody
    @Action(description = "附带检索条件的分页查询质量信得过职工管理", detail = "查询数据信息<#if success>成功<#else></#if>")
    public Object list(HttpServletRequest request) throws IllegalAccessException {
        QueryFilter queryFilter = new QueryFilter(request, true);
        // 默认按照创建时间倒序排列
        if (StringUtil.isEmpty(queryFilter.get("orderField"))) {
            queryFilter.addFilter("orderField", "createtime");
            queryFilter.addFilter("orderSeq", "desc");
        }
        ZhiLiangConst.addQueryFilter(queryFilter);
        //分页数据
        List<WQbdTrustPeople> pageDatas = wQbdTrustPeopleService.queryList(queryFilter);
        // 密级、上报状态、数据来源单位显示中文
        ZhiLiangConst.showName(pageDatas);
        // 添加编辑按钮权限控制
        ZhiLiangConst.isDataAllowEditByFlowStatus(pageDatas);
        SysAuditThreadLocalHolder.putParamerter("success", true);
        return success(pageDatas, queryFilter.getPageBean().getTotalCount());
    }


    /**
     * 功能描述: 跳转到新增页面
     *
     * @return: java.lang.String
     * @auther: 王明亮
     * @date: 2020-07-02 15:30:24
     */
    @RequestMapping(UrlConstants.VIEW_DISPATCH_PREFIX + UrlConstants.MODULE_FUNCTION_ADD_UPDATE)
    @Action(description = "跳转到质量信得过职工管理新增页面", exectype = "页面跳转日志")
    public String viewAdd(HttpServletRequest request, ModelMap modelMap) {
        String id = RequestUtil.getString(request, "id");
        modelMap.put("id", id);

        String flag = RequestUtil.getString(request, "flag");
        modelMap.put("flag", flag);
        String runId="";
        List<TaskOpinion> taskOpinionNewList = new ArrayList<TaskOpinion>();
        ProcessRun processRun=processRunService.getByBusinessKey(id);
        if(BeanUtils.isNotEmpty(processRun)){
            runId=processRun.getRunId();
            List<TaskOpinion> taskOpinionList = taskOpinionService.getByRunId(runId);
            for(TaskOpinion taskOpinion:taskOpinionList){
                if(taskOpinion.getEndTime()!=null){
                    taskOpinionNewList.add(taskOpinion);
                }
            }
        }
        modelMap.put("taskOpinionNewList", taskOpinionNewList);
        if (StringUtils.isNotBlank(id)) {
            WQbdTrustPeople wQbdTrustPeople = wQbdTrustPeopleService.getOneById(id);
            modelMap.put("flowStatus", wQbdTrustPeople.getFlowStatus());
        }

        return "wQbdTrustPeople/add";
    }

    /**
     * 功能描述:  数据保存通用方法
     *
     * @param: wQbdTrustPeople 保存的对象
     * @return: java.lang.Object
     * @auther: 王明亮
     * @date: 2020-07-02 15:30:24
     */
    @RequestMapping(UrlConstants.MODULE_FUNCTION_SAVE)
    @ResponseBody
    @Action(description = "保存质量信得过职工管理数据", detail = "<#if isAdd>新增<#else>编辑</#if>质量信得过职工管理数据<#if success>成功<#else>失败</#if><#if StringUtil.isNotEmpty(modifyInfo)>${modifyInfo}</#if>")
    public Object save(@RequestBody WQbdTrustPeople wQbdTrustPeople) {
        String id = wQbdTrustPeople.getId();
        int result;
        if (StringUtil.isEmpty(id)) {
            //新增操作
            //新增数据前生成随机Id
            wQbdTrustPeople.setId(ProjectUUIDUtils.getUUIDFor32());
            ZhiLiangConst.addCommonFields(wQbdTrustPeople);

            wQbdTrustPeople.setTenantId(ContextUtil.getCurrentUserTenantId());
            wQbdTrustPeople.setCreateBy(ContextUtil.getCurrentUserId());
            wQbdTrustPeople.setCreateTime(new Date());
            wQbdTrustPeople.setFlowStatus(FlowStatusEnum.NOT_SUBMIT.getValue());

            result = wQbdTrustPeopleService.add(wQbdTrustPeople);
            SysAuditThreadLocalHolder.putParamerter("isAdd", true);
        } else {
            SysAuditThreadLocalHolder.putParamerter("success", false);
            //修改操作
            ZhiLiangConst.updateCommonFields(wQbdTrustPeople);

            wQbdTrustPeople.setUpdateBy(ContextUtil.getCurrentUserId());
            wQbdTrustPeople.setUpdateTime(new Date());

            result = wQbdTrustPeopleService.update(wQbdTrustPeople);
            SysAuditThreadLocalHolder.putParamerter("modifyInfo", StructureModifyUtil.getModifyInfo(wQbdTrustPeopleService.getOneById(id), wQbdTrustPeople));
        }
        if (result > 0) {
            SysAuditThreadLocalHolder.putParamerter("success", true);
        } else {
            SysAuditThreadLocalHolder.putParamerter("success", false);
        }
        Map<String,Object> idMap= Maps.newHashMap();
        idMap.put("id",wQbdTrustPeople.getId());
        return result > 0 ? getResultDataSuccess("save.success",idMap) : getResultDataError("save.failure");
    }

    /**
     * 功能描述: 跳转到详情页面
     *
     * @return: java.lang.String
     * @auther: 王明亮
     * @date: 2020-07-02 15:30:24
     */
    @RequestMapping(UrlConstants.VIEW_DISPATCH_PREFIX + "/particulars")
    @Action(description = "跳转到质量信得过职工管理详情页面", exectype = "页面跳转日志")
    public String viewParticulars(HttpServletRequest request, ModelMap modelMap) {
        String flag = RequestUtil.getString(request, "flag");
        modelMap.put("flag", flag);
        String id = RequestUtil.getString(request,"id");
        modelMap.put("id",id);
        String isClose = RequestUtil.getString(request, "isClose");
        modelMap.put("isClose", isClose);
        String runId="";
        List<TaskOpinion> taskOpinionNewList = new ArrayList<TaskOpinion>();
        ProcessRun processRun=processRunService.getByBusinessKey(id);
        if(BeanUtils.isNotEmpty(processRun)){
            runId=processRun.getRunId();
            List<TaskOpinion> taskOpinionList = taskOpinionService.getByRunId(runId);
            for(TaskOpinion taskOpinion:taskOpinionList){
                if(taskOpinion.getEndTime()!=null){
                    taskOpinionNewList.add(taskOpinion);
                }
            }
        }
        modelMap.put("taskOpinionNewList", taskOpinionNewList);
        WQbdTrustPeople wQbdTrustPeople = wQbdTrustPeopleService.getOneById(id);
        modelMap.put("flowStatus", wQbdTrustPeople.getFlowStatus());
        modelMap.put("runId", runId);
        return "wQbdTrustPeople/particulars";
    }

    /**
     * 功能描述: 根据主键id获取一条数据的通用查询方法
     *
     * @param: id 参数对象必须是"id"
     * @return: java.lang.Object
     * @auther: 王明亮
     * @date: 2020-07-02 15:30:24
     */
    @RequestMapping(UrlConstants.MODULE_FUNCTION_GET)
    @ResponseBody
    @Action(description = "根据主键id查询质量信得过职工管理的一条数据", detail = "根据主键id查询质量信得过职工管理的数据<#if success>成功<#else>失败</#if>")
    public Object get(@RequestParam("id") String id) {
        WQbdTrustPeople wQbdTrustPeople = wQbdTrustPeopleService.getOneById(id);
        if (null == wQbdTrustPeople) {
            SysAuditThreadLocalHolder.putParamerter("success", false);
            return getResultDataError("get.failure");
        }
        FlowStatusEnum flowStatusEnum = FlowStatusEnum.getEnumByValue(wQbdTrustPeople.getFlowStatus());
        wQbdTrustPeople.setFlowStatusStr(flowStatusEnum.getName());
        SysAuditThreadLocalHolder.putParamerter("success", true);
        return getResultDataSuccess("get.success", wQbdTrustPeople);
    }

    /**
     * 功能描述: 根据主键ID删除数据的通用删除方法
     *
     * @param: id 参数名称必须是"id"
     * @return: java.lang.Object
     * @auther: 王明亮
     * @date: 2020-07-02 15:30:24
     */
    @PostMapping(UrlConstants.MODULE_FUNCTION_DELETE)
    @ResponseBody
    @Action(description = "根据主键ID删除质量信得过职工管理数据", exectype = "删除日志", detail = "删除数据信息<#if success>成功<#else>失败</#if>")
    public Object delete(@RequestParam("id") String id) throws Exception{
        String userId = ContextUtil.getCurrentUserId();
        String[] ids = id.split(",");
        for (String key : ids) {
            WQbdTrustPeople wQbdTrustPeople = wQbdTrustPeopleService.getOneById(key);
            if (!userId.equals(wQbdTrustPeople.getCreateBy())) {
                SysAuditThreadLocalHolder.putParamerter("success", false);
                return fail("删除失败，只能删除自己创建的数据！");
            }
            //判断流程状态
            FlowStatusEnum flowStatusEnum = FlowStatusEnum.getEnumByValue(wQbdTrustPeople.getFlowStatus());
            if (!flowStatusEnum.isDel()) {
                SysAuditThreadLocalHolder.putParamerter("success", false);
                return fail("删除失败，不允许删除流程未结束数据！");
            }
        }
        if (StringUtil.isEmpty(id)) {
            SysAuditThreadLocalHolder.putParamerter("success", false);
            return fail("delete.failure.message");
        }
        //流程实例删除
        for (String key : ids) {
            WQbdTrustPeople wQbdTrustPeople = wQbdTrustPeopleService.getOneById(key);
            if(!wQbdTrustPeople.getFlowStatus().equals(FlowStatusEnum.NOT_SUBMIT.getValue()) && StringUtil.isNotEmpty(wQbdTrustPeople.getFlowStatus())){
                ProcessRun processRun = processRunService.getByBusinessKey(key);
                if(processRun!=null){
                    processRunService.deleteByProcessRun(processRun);
                }
            }
        }
        int result = wQbdTrustPeopleService.delByIdArray(id.split(","));
        if (result > 0) {
            SysAuditThreadLocalHolder.putParamerter("success", true);
        } else {
            SysAuditThreadLocalHolder.putParamerter("success", false);
        }
        return result > 0 ? getResultDataSuccess("delete.success") : getResultDataError("delete.failure");
    }

    /**
     * 功能描述: 跳转到导出选择字段页面
     *
     * @param request
     * @param modelMap
     * @return
     * @throws Exception
     */
    @RequestMapping(UrlConstants.VIEW_DISPATCH_PREFIX + "/export")
    @Action(description = "跳转到质量信得过职工管理导出选择字段页面", exectype = "页面跳转日志")
    public String export(HttpServletRequest request, ModelMap modelMap) throws Exception {
        com.alibaba.fastjson.JSONObject jsonObject = AuxiliaryUtil.resolverModel(WQbdTrustPeople.class);
        modelMap.put("tableInfo", jsonObject.toString());
        return "expImp/add";
    }

    /**
     * 功能描述: 导出质量信得过职工管理数据信息
     *
     * @param: [request] http请求
     * @return: java.lang.Object
     * @auther: 王明亮
     * @date: 2020-07-02 15:30:24
     */
    @RequestMapping("/exportData")
    @Action(description = "导出质量信得过职工管理数据信息", detail = "导出质量信得过职工管理数据信息<#if success>成功<#else></#if>")
    public void export(HttpServletRequest request, HttpServletResponse response) throws Exception {
        SysAuditThreadLocalHolder.putParamerter("success", false);
        String[] id = RequestUtil.getStringAryByStr(request, "id");
        QueryFilter queryFilter = new QueryFilter(request, false);
        JSONArray dataArray = ZhiLiangConst.exportAddConditions(queryFilter, id);
        List<WQbdTrustPeople> wQbdTrustPeopleList = this.wQbdTrustPeopleService.queryAll(queryFilter);
        if (wQbdTrustPeopleList.isEmpty()) {
            wQbdTrustPeopleList.add(new WQbdTrustPeople());
        }
        new AbstractExpUtil() {
            @Override
            public String customAnalysis(String fieldName, String fieldValue) {
                return null;
            }
        }.executeExport(request, response, wQbdTrustPeopleList, dataArray, AbstractExpUtil.ExpStyle.MANY_SHEET);
        SysAuditThreadLocalHolder.putParamerter("success", true);
    }

    /**
     * 功能描述: 启动流程
     */
    @PostMapping("/run")
    @ResponseBody
    @Action(description="启动质量信得过职工流程",detail="启动流程<#if success>成功<#else></#if>")
    public Object run(HttpServletRequest request,@RequestBody WQbdTrustPeople wQbdTrustPeople){
        SysUser sysUser = (SysUser) ContextUtil.getCurrentUser();
        //实体主键
        String id = wQbdTrustPeople.getId();
        int isList = RequestUtil.getInt(request,"isList",1);
        ProcessCmd processCmd = new ProcessCmd();
        //流程Key
        processCmd.setModelKey("zlxdgzgsplc");
        processCmd.setUserAccount(sysUser.getAccount());
        try {
            if(isList == 1){
                wQbdTrustPeople = wQbdTrustPeopleService.getOneById(id);
            }
            processCmd.setBusinessKey(id);
            processRunService.startProcess(processCmd);
            wQbdTrustPeople.setFlowStatus(FlowStatusEnum.APPROVAL_ING2.getValue());
            wQbdTrustPeopleService.update(wQbdTrustPeople);
            SysAuditThreadLocalHolder.putParamerter("success",true);
            return getResultDataSuccess("flow.start.success");
        } catch (Exception e) {
            SysAuditThreadLocalHolder.putParamerter("success",false);
            return getResultDataError("flow.start.failure");
        }
    }

}
